<?php

error_reporting(E_ALL);
ini_set("display_erros", 1);

if (!isset($_SERVER["argc"]) or $_SERVER["argc"] != 3)
{
	echo "The script requires 2 parameters:\n";
	echo "1) sessions directory WITHOUT terminal slash,\n";
	echo "2) log directory (where file sessions_clean.log will be created) WITHOUT terminal slash.\n";
	die(1);
}

$sessions_dir = $_SERVER["argv"][1];
$log_dir = $_SERVER["argv"][2];

$stat_file_count = 0;
$stat_members_file_count = 0;
$stat_deleted_file_count = 0;
$stat_bad_files = 0;

$time = time();
$start_time = microtime(true);

foreach(scandir($sessions_dir) as $file)
{
	if (substr($file, -8, 8) == ".session")
	{
		$stat_file_count++;
		$file_contents = file_get_contents($sessions_dir . "/" . $file);
		$data = unserialize($file_contents);
		$unlink = false;
		if (isset($data["member_id"]))
		{
			$stat_members_file_count++;
		}
		if (isset($data["x_session"]["expires_time"]))
		{
			if ($data["x_session"]["expires_time"] <= $time)
			{
				$unlink = true;
			}
		}
		else
		{
			$unlink = true;
			$stat_bad_files++;
		}
		if ($unlink)
		{
			$stat_deleted_file_count++;
			unlink($sessions_dir . "/" . $file);
		}
	}
}

$time = microtime(true) - $start_time;
$log = "[" . date("r", $time) . "]\tfiles:\t{$stat_file_count}\tmember's:\t{$stat_members_file_count}\tdeleted:\t{$stat_deleted_file_count}\tbad:\t{$stat_bad_files}\ttime:\t{$time}\n";
file_put_contents($log_dir . "/sessions_clean.log", $log, FILE_APPEND);

?>